﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using CNKI.TPI.Web.UI.Filters;
using CNKI.TPI.Web.UI.Models;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.Model;
using CNKI.TPI.Web.Base;
using Castle.DynamicProxy;
using System.Security.Cryptography;
using System.Text;
using CNKI.TPI.Web.Admin.Model;

namespace CNKI.TPI.Web.UI.Controllers.Search
{
    //[Authorize]
    //[InitializeSimpleMembership]
    public class AccountController : BaseController
    {
        private IUserService userService = null;
        private ITopicService topicService = null;
        public AccountController(ITopicService subjectService, IUserService userService)
        {
            this.topicService = generator.CreateInterfaceProxyWithTarget<ITopicService>(subjectService, new IInterceptor[] { new LogInterceptor() });
            this.userService = generator.CreateInterfaceProxyWithTarget<IUserService>(userService, new IInterceptor[] { new LogInterceptor() }); ;
        }
        //
        // GET: /Account/Login

        public ActionResult Login(string returnUrl)
        {
            if (null != returnUrl)
            {
                string topicCode = "";
                string layout = "~/Views/Shared/_Layout.cshtml";
                if (!String.IsNullOrEmpty(Request.QueryString["TopicCode"]))
                {
                    topicCode = Request.QueryString["TopicCode"];
                }
                IList<SYS_CMS_TOPIC> topicInfo = topicService.GetTopicInfo(topicCode);
                if (topicInfo != null && topicInfo.Count > 0)
                {
                    ViewBag.TitlePic = topicInfo[0].TopicPic;
                    ViewBag.TitleTopic = topicInfo[0].TopicName;
                    ViewBag.CopyRight = topicInfo[0].CopyRight;
                    layout = "~/Views/Shared/_LayoutTopicLogin.cshtml";
                }
                ViewBag.DateStr = System.DateTime.Now.ToString("yyyy-MM-dd") + "  " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek); ;
                ViewBag.TopicCode = topicCode;
                ViewBag.Layout = layout;
                ViewBag.ReturnUrl = returnUrl;
            }
            else
            {
                //ViewBag.ReturnUrl = Request.UrlReferrer.AbsolutePath;
            }
            ViewBag.FaildNum=userService.GetFaidNum();
            return View();
        }

        public ActionResult LoginSSO(string returnUrl)
        {
            string app = HttpRuntime.AppDomainAppVirtualPath;
            if (!app.EndsWith("/"))
                app += "/";
            return Redirect(string.Format("{0}sso/login.ashx?returnurl={1}", app, Uri.EscapeDataString(returnUrl)));
        }

        [AllowAnonymous]
        public ActionResult MiddleJump(string returnUrl)
        {
            if (null != returnUrl)
            {
                ViewBag.ReturnUrl = returnUrl;
            }
            else
            {
                //ViewBag.ReturnUrl = Request.UrlReferrer.AbsolutePath;
            }
            return View();
        }


        //
        // POST: /Account/LogOff

        //[HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            SessionHelper.ClearUserInfo();
            bool anonymousControlFlag = ConfigHelper.IsAnonymousControlEnabled();
            if (anonymousControlFlag)
            {
                string anonymousUsername = ConfigHelper.GetAnonymousAccount();
                LoginUserInfo userinfo = userService.ValidateUser(anonymousUsername, "", false);
                if (null != userinfo && userinfo.status == LoginUserInfo.MessageFlage.Success)
                {
                    SessionHelper.SetUserInfo(userinfo);
                }
            }

            string topicCode = Request["TopicCode"];
            IList<SYS_CMS_TOPIC> topicInfo = topicService.GetTopicInfo(topicCode);
            if (topicCode != null && topicInfo.Count > 0)
            {
                return Redirect("http://" + topicInfo[0].Domain);
            }
            //WebSecurity.Logout();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOffSSO()
        {
            FormsAuthentication.SignOut();
            SessionHelper.ClearUserInfo();
            bool anonymousControlFlag = ConfigHelper.IsAnonymousControlEnabled();
            if (anonymousControlFlag)
            {
                string anonymousUsername = ConfigHelper.GetAnonymousAccount();
                LoginUserInfo userinfo = userService.ValidateUser(anonymousUsername, "", false);
                if (null != userinfo && userinfo.status == LoginUserInfo.MessageFlage.Success)
                {
                    SessionHelper.SetUserInfo(userinfo);
                }
            }
            string app = HttpRuntime.AppDomainAppVirtualPath;
            if (!app.EndsWith("/"))
                app += "/";
            return Redirect("~/sso/logout.ashx?ReturnUrl=" + Uri.EscapeDataString(Request.Url.GetLeftPart(UriPartial.Authority)+(app=="/"?"":app)));
        }

        //
        // GET: /Account/Register
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        [SecurityActionFilter]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            int m = userService.GetFaidNum();
            ViewBag.FaildNum = m;
            if (m>= 2)
            {
                if (Session["Code"] != null && model.VerificationCode.ToLower() != Session["Code"].ToString().ToLower())
                {
                    ModelState.AddModelError("", "验证码错误");
                    return View(model);
                }
            }
            if (!string.IsNullOrEmpty(returnUrl))
            {
                ViewBag.ReturnUrl = returnUrl;
            }

            var loginKey = TempData["LoginKey"];
            if (loginKey == null || loginKey.ToString() != model.LoginKey)
            {
                ModelState.AddModelError("", "登陆过期,请重新登陆");
                return View(model);
            }

            //解密密码
            if (model.Password != null && model.Password != "" && ConfigHelper.IsEncryptPasswordEnabled())
            {
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString((string)TempData["RSAKey"]);
                byte[] result = rsa.Decrypt(HexStringToBytes(model.Password), false);
                System.Text.ASCIIEncoding enc = new ASCIIEncoding();
                model.Password = enc.GetString(result);
            }

            LoginUserInfo user = userService.ValidateUser(model.UserName, model.Password);
            if (null != user)
            {
                //FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                //    1,
                //    string.IsNullOrEmpty(user.UserName) ? user.UserCode : user.UserName,
                //    DateTime.Now,
                //    DateTime.Now.AddMinutes(30),
                //    true,
                //    user.UserCode + ":" + string.Join(",", user.Role.Select(p => p.Name))
                //    );
                //string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                //System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                //System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
                //FormsAuthentication.SetAuthCookie(string.IsNullOrEmpty(user.UserName) ? user.UserCode : user.UserName, true);
               
                if (user.status == LoginUserInfo.MessageFlage.StopError)
                {
                    ModelState.AddModelError("", "用户已经被停用！");
                    return View(model);
                }
                else if (user.status == LoginUserInfo.MessageFlage.IpError)
                {
                    ModelState.AddModelError("", "IP地址不在范围内！");
                    return View(model);

                }
                else if (user.status == LoginUserInfo.MessageFlage.PasswordError)
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确");
                    return View(model);
                }
                else if (user.status == LoginUserInfo.MessageFlage.Expire)
                {
                    ModelState.AddModelError("", "用户已经过期");
                    return View(model);
                }
                else
                {
                    SessionHelper.ClearUserInfo();
                    SessionHelper.SetUserInfo(user);
                    return RedirectToLocal(returnUrl);
                }

            }
            //if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            //{
            //    return RedirectToLocal(returnUrl);
            //}

            // 如果我们进行到这一步时某个地方出错，则重新显示表单

            ModelState.AddModelError("", "提供的用户名或密码不正确");
            return View(model);
        }

        public string GetRSAKey()
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);
            TempData["RSAKey"] = rsa.ToXmlString(true);
            RSAParameters parameter = rsa.ExportParameters(true);
            string strPublicKeyExponent = BytesToHexString(parameter.Exponent);
            string strPublicKeyModulus = BytesToHexString(parameter.Modulus);
            string loginKey = StringHelper.GetMD5(strPublicKeyModulus);
            TempData["LoginKey"] = loginKey;
            return strPublicKeyExponent + "|" + strPublicKeyModulus+"|"+loginKey;
        }

        private string BytesToHexString(byte[] input)
        {
            StringBuilder hexString = new StringBuilder(64);

            for (int i = 0; i < input.Length; i++)
            {
                hexString.Append(String.Format("{0:X2}", input[i]));
            }
            return hexString.ToString();
        }

        public static byte[] HexStringToBytes(string hex)
        {
            if (hex.Length == 0)
            {
                return new byte[] { 0 };
            }

            if (hex.Length % 2 == 1)
            {
                hex = "0" + hex;
            }

            byte[] result = new byte[hex.Length / 2];

            for (int i = 0; i < hex.Length / 2; i++)
            {
                result[i] = byte.Parse(hex.Substring(2 * i, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
            }

            return result;
        }

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        //
        // POST: /Account/Disassociate

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;

            // 只有在当前登录用户是所有者时才取消关联帐户
            if (ownerAccount == User.Identity.Name)
            {
                // 使用事务来防止用户删除其上次使用的登录凭据
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return RedirectToAction("Manage", new { Message = message });
        }

        //
        // GET: /Account/Manage

        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "已更改你的密码。"
                : message == ManageMessageId.SetPasswordSuccess ? "已设置你的密码。"
                : message == ManageMessageId.RemoveLoginSuccess ? "已删除外部登录。"
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // 在某些失败方案中，ChangePassword 将引发异常，而不是返回 false。
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "当前密码不正确或新密码无效。");
                    }
                }
            }
            else
            {
                // 用户没有本地密码，因此将删除由于缺少
                // OldPassword 字段而导致的所有验证错误
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", e);
                    }
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // 如果当前用户已登录，则添加新帐户
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // 该用户是新用户，因此将要求该用户提供所需的成员名称
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            }
        }

        //
        // POST: /Account/ExternalLoginConfirmation

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // 将新用户插入到数据库
                //using (UsersContext db = new UsersContext())
                //{
                //    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                //    // 检查用户是否已存在
                //    if (user == null)
                //    {
                //        // 将名称插入到配置文件表
                //        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                //        db.SaveChanges();

                //        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                //        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                //        return RedirectToLocal(returnUrl);
                //    }
                //    else
                //    {
                //        ModelState.AddModelError("UserName", "用户名已存在。请输入其他用户名。");
                //    }
                //}
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }

        //
        // GET: /Account/ExternalLoginFailure

        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            List<ExternalLogin> externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                {
                    Provider = account.Provider,
                    ProviderDisplayName = clientData.DisplayName,
                    ProviderUserId = account.ProviderUserId,
                });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        #region 帮助程序
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // 请参见 http://go.microsoft.com/fwlink/?LinkID=177550 以查看
            // 状态代码的完整列表。
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "用户名已存在。请输入其他用户名。";

                case MembershipCreateStatus.DuplicateEmail:
                    return "该电子邮件地址的用户名已存在。请输入其他电子邮件地址。";

                case MembershipCreateStatus.InvalidPassword:
                    return "提供的密码无效。请输入有效的密码值。";

                case MembershipCreateStatus.InvalidEmail:
                    return "提供的电子邮件地址无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidAnswer:
                    return "提供的密码取回答案无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidQuestion:
                    return "提供的密码取回问题无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidUserName:
                    return "提供的用户名无效。请检查该值并重试。";

                case MembershipCreateStatus.ProviderError:
                    return "身份验证提供程序返回了错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                case MembershipCreateStatus.UserRejected:
                    return "已取消用户创建请求。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                default:
                    return "发生未知错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";
            }
        }
        #endregion
    }
}
